import os
import time
import warnings

import pandas as pd
from openpyxl.workbook import Workbook

from httpTasks.httpRegistrationAndAuthorization import register, authorize
from mqtt.mQTTClient import MqttClient
from objects import globalVariable

# 忽略特定的警告
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")


def operate():
    # 获取当前工作目录
    current_dir = os.getcwd()
    print("当前工作目录:", current_dir)
    file_name = 'readWriteExcel\\license.xlsx'
    file_path = os.path.join(current_dir, file_name)
    # 读取整个 Excel 文件
    df = pd.read_excel(file_path, engine='openpyxl')
    # 打印原始数据
    print("原始数据：")
    print(df)
    # 创建一个新的工作簿
    wb = Workbook()
    # 获取默认的工作表
    ws = wb.active
    # 添加标题行
    ws.append(["clientNo", "license", "clientId", "groupId", "uname", "pwd", "mqtthost", "port", "scope", "eew_topic",
               "eqr_topic", "ack_topic", "online"])
    # 按行迭代并处理
    for index, row in df.iterrows():
        # 获取当前行的 Score 值
        globalVariable.clientNo = row['终端序列号']
        globalVariable.license = row['许可证号']
        globalVariable.groupId, globalVariable.clientId, globalVariable.uname, globalVariable.pwd = register(license)
        (globalVariable.eew_topic, globalVariable.eqr_topic,
         globalVariable.ack_topic, globalVariable.mqtthost, globalVariable.port, globalVariable.scope) = authorize(
            globalVariable.clientId, globalVariable.uname, globalVariable.pwd)
        MqttClient.publish(globalVariable.client_keson, 'action/' + globalVariable.clientNo,
                           f'{"clients":["{globalVariable.clientNo}"],"todo":"readConfig"}')
        count_time, online = 0, True
        while globalVariable.offline_flag or count_time <= 10:
            count_time += 1
            time.sleep(1)
        if globalVariable.offline_flag:
            globalVariable.offline_flag = True
            online = False
        # 添加数据行
        row = [globalVariable.clientNo, globalVariable.license, globalVariable.clientId, globalVariable.groupId,
               globalVariable.uname, globalVariable.pwd, globalVariable.mqtthost, globalVariable.port,
               globalVariable.scope, globalVariable.eqr_topic, globalVariable.ack_topic, globalVariable.ack_topic,
               online]
        ws.append(row)

        print(f"终端序列号: {globalVariable.clientNo},许可证号: {license}")
